package com.rp.system.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rp.common.utils.RpUtil;
import com.rp.log.annotation.RpLog;
import com.rp.system.dao.RoleDao;
import com.rp.system.dao.UserDao;
import com.rp.system.po.Role;
import com.rp.system.po.User;

@Service
@Transactional
public class RoleService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	
	/**
	 * 添加角色
	 * @param name
	 * @return
	 */
	@RpLog(desc="添加角色")
	public String addRole(String name){
		Role role = new Role();
		role.setName(name);
		role.setSuperRole("0");
		role.setCreateDate(RpUtil.getCurrentDatetime());
		return (String) roleDao.save(role);
	}
	
	/**
	 * 删除角色
	 * @param roleId
	 */
	@RpLog(desc="删除角色")
	public void deleteRole(String roleId){
		Role role = roleDao.get(roleId);
		
		List<User> users = userDao.find("from User where roleId = ?", roleId);
		if(users.size() > 0){
			for (User user : users) {
				user.setRoleId(null);
				user.setRoleName(null);
			}
		}
		
		role.setAuthorities(null);
		roleDao.delete(role);
	}
	
	/**
	 * 更新角色
	 * @param role
	 */
	@RpLog(desc="更新角色")
	public void updateRole(Role role){
		
		List<User> users = userDao.find("from User where roleId = ?", role.getId());
		if(users.size() > 0){
			for (User user : users) {
				user.setRoleName(role.getName());
			}
		}
		
		role.setUpdateDate(RpUtil.getCurrentDatetime());
		roleDao.update(role);
	}
	
	
	public RoleDao getRoleDao() {
		return roleDao;
	}
	
}
